#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import re
from pystardict import Dictionary
import sqlite3
cwd= os.getcwd()
input_file = os.path.join(cwd, 'words.txt')

dict1 = Dictionary(os.path.join(cwd, 'stardict-xhzd-2.4.2', 'xhzd'))

sql_create = 'create table dict(id INTEGER PRIMARY KEY AUTOINCREMENT, word text UNIQUE, mean text)'
db1 = sqlite3.connect( os.path.join(cwd, 'mydict.db') )
db1.text_factory = str
cu1 = db1.cursor()
try:
    cu1.execute( sql_create)
except:
    pass
cu1.close()
    


def output_db( keys ):
    for key1 in keys:
        try:
            sql1 = "insert into dict(word,mean) values(? , ?)" 
            cu1 = db1.cursor()
            cu1.execute( sql1,  (key1,  re.sub( '<br>', '\n',  dict1.dict[key1] )) )
            cu1.close()
        except:
            pass
    return 0
    
def file_input(filep1):
    file1=open(filep1)
    for s1 in file1:
        sp1=[]
        if len(s1)>0:
            sp2=re.split('[ \t\n]+',s1)
            for s2 in sp2:
                if len(s2)>0:
                    sp1+=[s2,]
        output_db(sp1)
    file1.close()
    return 0

if __name__ == '__main__':
    file_input(input_file)
    cu1.close()
    db1.commit()
    db1.close()
